/**
 * 方案比对页面 Mock 数据
 * 用于界面预览和开发测试
 */

/**
 * 生成随机日期时间
 */
const getRandomDateTime = (baseDate, hourOffset, durationHours) => {
  const date = new Date(baseDate)
  date.setHours(date.getHours() + hourOffset)
  const startTime = date.toISOString().slice(0, 19).replace('T', ' ')
  
  date.setHours(date.getHours() + durationHours)
  const endTime = date.toISOString().slice(0, 19).replace('T', ' ')
  
  return { startTime, endTime, duration: durationHours }
}

/**
 * 约束配置列表（模拟 4 个方案）
 */
export const mockConstraints = [
  {
    id: 'constraint-001',
    title: '方案1 - SPT优先策略',
    constraintName: 'SPT优先策略',
    checked: false,
    createTime: '2025-10-23 08:00:00',
    updateTime: '2025-10-23 08:00:00'
  },
  {
    id: 'constraint-002',
    title: '方案2 - EDD交期优先',
    constraintName: 'EDD交期优先',
    checked: false,
    createTime: '2025-10-23 08:15:00',
    updateTime: '2025-10-23 08:15:00'
  },
  {
    id: 'constraint-003',
    title: '方案3 - 资源均衡策略',
    constraintName: '资源均衡策略',
    checked: false,
    createTime: '2025-10-23 08:30:00',
    updateTime: '2025-10-23 08:30:00'
  },
  {
    id: 'constraint-004',
    title: '方案4 - 遗传算法优化',
    constraintName: '遗传算法优化',
    checked: false,
    createTime: '2025-10-23 08:45:00',
    updateTime: '2025-10-23 08:45:00'
  }
]

/**
 * 甘特图数据生成器
 */
export const generateGanttData = (constraintId) => {
  const baseDate = '2025-10-23'
  const devices = [
    { code: 'DEV001', name: '加工中心-01' },
    { code: 'DEV002', name: '加工中心-02' },
    { code: 'DEV003', name: '数控车床-01' },
    { code: 'DEV004', name: '数控车床-02' },
    { code: 'DEV005', name: '磨床-01' }
  ]
  
  const products = ['PROD001', 'PROD002', 'PROD003', 'PROD004', 'PROD005']
  const orders = ['ORD001', 'ORD002', 'ORD003', 'ORD004', 'ORD005', 'ORD006']
  
  // 根据不同约束生成不同的排程
  const constraintIndex = mockConstraints.findIndex(c => c.id === constraintId)
  const offset = constraintIndex * 0.5 // 不同方案有不同的时间偏移
  
  return devices.map((device, deviceIndex) => {
    const taskCount = 2 + Math.floor(Math.random() * 3) // 每个设备 2-4 个任务
    const tasks = []
    
    let currentHour = 8 + offset // 从早上 8 点开始
    
    for (let i = 0; i < taskCount; i++) {
      const duration = 2 + Math.floor(Math.random() * 4) // 2-5 小时
      const orderIndex = (deviceIndex + i) % orders.length
      const productIndex = (deviceIndex + i) % products.length
      
      const { startTime, endTime } = getRandomDateTime(baseDate, currentHour, duration)
      
      tasks.push({
        orderId: `ORDER${String(orderIndex + 1).padStart(3, '0')}`,
        orderCode: orders[orderIndex],
        productCode: products[productIndex],
        processCode: `PROC${String(i + 1).padStart(3, '0')}`,
        processName: `工序${i + 1}`,
        startTime,
        endTime,
        duration,
        quantity: 50 + Math.floor(Math.random() * 100),
        status: currentHour < 12 ? 'completed' : currentHour < 16 ? 'inProgress' : 'pending'
      })
      
      currentHour += duration + 0.5 // 任务间隔 0.5 小时
    }
    
    return {
      deviceCode: device.code,
      deviceName: device.name,
      tasks
    }
  })
}

/**
 * 计划详情表格数据生成器
 */
export const generatePlanDetailData = (constraintId) => {
  const ganttData = generateGanttData(constraintId)
  const detailData = []
  
  ganttData.forEach(device => {
    device.tasks.forEach((task, index) => {
      detailData.push({
        id: `${device.deviceCode}-${task.orderCode}-${index}`,
        deviceCode: device.deviceCode,
        deviceName: device.deviceName,
        orderCode: task.orderCode,
        productCode: task.productCode,
        quantity: task.quantity,
        priority: ['高', '中', '低'][Math.floor(Math.random() * 3)],
        processCode: task.processCode,
        processName: task.processName,
        standardTime: task.duration,
        startTime: task.startTime,
        endTime: task.endTime,
        status: task.status
      })
    })
  })
  
  return detailData
}

/**
 * KPI 指标数据生成器
 */
export const generateMetricsData = (constraintId) => {
  const constraintIndex = mockConstraints.findIndex(c => c.id === constraintId)
  
  // 不同方案的指标略有差异
  const baseMetrics = {
    deliveryRate: 92 + constraintIndex * 1.5,      // 交期完成率 92-97%
    equipmentUtilization: 84 + constraintIndex * 1.2, // 设备利用率 84-88%
    actualCapacity: 1150 + constraintIndex * 30,    // 实际产能 1150-1240
    avgWorkTime: 7.2 - constraintIndex * 0.15       // 平均工时 6.75-7.2h
  }
  
  return {
    ...baseMetrics,
    // 添加更多详细指标
    totalOrders: 18 + Math.floor(Math.random() * 5),
    completedOrders: Math.floor((18 + Math.random() * 5) * baseMetrics.deliveryRate / 100),
    delayedOrders: Math.floor((18 + Math.random() * 5) * (100 - baseMetrics.deliveryRate) / 100),
    totalWorkTime: Math.floor(baseMetrics.avgWorkTime * 20),
    idleTime: Math.floor((100 - baseMetrics.equipmentUtilization) * 2),
    setupTime: Math.floor(Math.random() * 10) + 5
  }
}

/**
 * 所有方案的指标对比数据
 */
export const generateAllPlansMetrics = () => {
  return mockConstraints.map((constraint, index) => ({
    constraintId: constraint.id,
    constraintTitle: constraint.title,
    metrics: generateMetricsData(constraint.id),
    // 设备级别的利用率数据（用于趋势图）
    deviceUtilization: [
      { deviceCode: 'DEV001', deviceName: '加工中心-01', utilization: 82 + index * 2 + Math.random() * 3 },
      { deviceCode: 'DEV002', deviceName: '加工中心-02', utilization: 85 + index * 1.5 + Math.random() * 3 },
      { deviceCode: 'DEV003', deviceName: '数控车床-01', utilization: 88 + index * 1 + Math.random() * 3 },
      { deviceCode: 'DEV004', deviceName: '数控车床-02', utilization: 84 + index * 1.8 + Math.random() * 3 },
      { deviceCode: 'DEV005', deviceName: '磨床-01', utilization: 80 + index * 2.2 + Math.random() * 3 }
    ],
    // 时间段利用率数据
    timeSlotUtilization: [
      { time: '08:00', utilization: 75 + Math.random() * 5 },
      { time: '10:00', utilization: 82 + Math.random() * 5 },
      { time: '12:00', utilization: 88 + Math.random() * 5 },
      { time: '14:00', utilization: 85 + Math.random() * 5 },
      { time: '16:00', utilization: 90 + Math.random() * 5 },
      { time: '18:00', utilization: 87 + Math.random() * 5 }
    ],
    // 设备产能数据
    deviceCapacity: [
      { deviceCode: 'DEV001', capacity: 220 + index * 10 + Math.random() * 20 },
      { deviceCode: 'DEV002', capacity: 190 + index * 12 + Math.random() * 20 },
      { deviceCode: 'DEV003', capacity: 240 + index * 8 + Math.random() * 20 },
      { deviceCode: 'DEV004', capacity: 210 + index * 11 + Math.random() * 20 },
      { deviceCode: 'DEV005', capacity: 200 + index * 9 + Math.random() * 20 }
    ],
    // 交期完成情况
    deliveryStatus: {
      onTime: 45 + Math.floor(Math.random() * 8),
      delayed: 5 - Math.floor(Math.random() * 3),
      early: 10 + Math.floor(Math.random() * 5)
    }
  }))
}

/**
 * 约束详情数据生成器
 */
export const generateConstraintDetail = (constraintId) => {
  const constraint = mockConstraints.find(c => c.id === constraintId)
  
  if (!constraint) return null
  
  return {
    ...constraint,
    description: `${constraint.title}的详细配置说明`,
    algorithmType: ['SPT', 'EDD', 'CR', 'GENETIC'][mockConstraints.findIndex(c => c.id === constraintId)],
    parameters: {
      priority: 'high',
      optimizationGoal: 'minimize_makespan',
      constraints: [
        '设备能力约束',
        '工序顺序约束',
        '交期约束'
      ]
    },
    baseParameters: {
      planningHorizon: 7, // 计划周期（天）
      timeGranularity: 1, // 时间粒度（小时）
      allowOvertime: true // 允许加班
    },
    statistics: {
      totalProcessed: 18 + Math.floor(Math.random() * 5),
      avgProcessingTime: 6.5 + Math.random() * 1.5,
      resourceUtilization: 85 + Math.random() * 5
    }
  }
}

/**
 * 完整的方案数据获取（模拟 API 调用）
 */
export const getPlanComparisonData = async (constraintId) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  
  return {
    success: true,
    code: 200,
    message: '获取成功',
    data: {
      constraintId,
      constraint: generateConstraintDetail(constraintId),
      ganttData: generateGanttData(constraintId),
      planDetailData: generatePlanDetailData(constraintId),
      metrics: generateMetricsData(constraintId),
      timestamp: new Date().toISOString()
    }
  }
}

/**
 * 获取所有方案对比数据
 */
export const getAllPlansComparisonData = async (constraintIds) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  const plans = constraintIds.map(id => {
    const constraint = mockConstraints.find(c => c.id === id)
    return {
      constraintId: id,
      constraintTitle: constraint?.title || '未知方案',
      metrics: generateMetricsData(id)
    }
  })
  
  return {
    success: true,
    code: 200,
    message: '获取成功',
    data: {
      plans,
      comparison: generateAllPlansMetrics(),
      timestamp: new Date().toISOString()
    }
  }
}

/**
 * 获取约束列表（模拟 API）
 */
export const getConstraintsList = async () => {
  await new Promise(resolve => setTimeout(resolve, 200))
  
  return {
    success: true,
    code: 200,
    message: '获取成功',
    data: mockConstraints
  }
}

// 默认导出
export default {
  mockConstraints,
  generateGanttData,
  generatePlanDetailData,
  generateMetricsData,
  generateAllPlansMetrics,
  generateConstraintDetail,
  getPlanComparisonData,
  getAllPlansComparisonData,
  getConstraintsList
}

